﻿using System;
using System.ServiceProcess;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace TeamDeploy.Tasks
{
    public class StopService :TaskBase
    {
        public override bool Execute()
        {
            try
            {
                ServiceController controller = new ServiceController(ServiceName, TargetMachine);

                try
                {
                    if (!controller.CanStop)
                        return true;
                }
                catch (Exception)
                {
                    Log.LogMessage("Stop Service: " + ServiceName + " on " + TargetMachine + " doesn't exist.");
                    return true;
                }
                   
                if (controller != null && controller.CanStop)
                {
                    controller.Stop();
                }
                    if (BuildEngine != null)
                {
                    Log.LogMessage("Stop Service: " + ServiceName + " on " + TargetMachine + " completed successfully.");
                }
                return true;
            }
            catch (Exception ex)
            {
                if (BuildEngine != null)
                {
                    Log.LogError("Error stopping service: " + ServiceName + " TargetMachine=" + TargetMachine + ":::" +
                                 ex);
                }
                return false;
            }
        }

        [Required]
        public string ServiceName { get; set; }

        [Required]
        public string TargetMachine { get; set; }
    }
}
